import { defineComponent, onMounted, reactive, ref, toRefs, unref } from 'vue'
import { Card, Button, Table, Space, Row, Col, Select, FormItem, datePi, DatePicker, RangePicker } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useColumns } from './use-columns'
import DataDetail from './detail'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { takeFinishStatus } from '@/views/task/task-publish/data'
import { addressTypeObj } from '@/views/task/task-publish/data'

const TaskPublish = defineComponent({
  name: 'TaskPublish',
  setup() {
    const tableLoading = ref<boolean>(false)
    const tableData = ref<any[]>([])
    const pageType = ref<BusinessPageTypeEnum>(BusinessPageTypeEnum.TABLE)
    const addressOptionData = ref<any[]>([]) //位置
    const warehouseOptionData = ref<any[]>([]) //仓库
    const storeOptionData = ref<any[]>([]) //产品
    const tagListData = ref<any[]>([]) //标签
    const selectData = reactive({
      code: null as string | null
    })
    const tableTotal = ref<any>({
      currPage: 1,
      totalCount: 0,
      totalPage: 0,
      pageSize: 10
    })
    const tableQuery = reactive({
      addressType: null as string | null,
      addressCode: null as string | null,
      tagCodeList: null as string | null,
      status: null,
      deadlineStart: null,
      deadlineEnd: null,
      pageNum: 1,
      pageSize: 10
    })
    const { status, getDataList, getWarehouseList, getStoreOptions, getTagList, finishTask } = useDetail()

    const updateData = (code: string) => {
      pageType.value = BusinessPageTypeEnum.UPDATE
      selectData.code = code
    }

    const detailData = (code: string) => {
      pageType.value = BusinessPageTypeEnum.DETAIL
      selectData.code = code
    }

    const finishData = async (code: string) => {
      await finishTask(code, takeFinishStatus[2].value)
      await fetchData()
    }

    // 处理选择框的onChange事件
    const addressChange = value => {
      if (value == '1') {
        //仓库
        addressOptionData.value = warehouseOptionData.value
      } else if (value == '2') {
        //门店
        addressOptionData.value = storeOptionData.value
      }
      tableQuery.addressCodeList = null
    }

    const { getColumns, tableColumns } = useColumns(updateData, detailData, finishData)

    const onSearch = async () => {
      tableQuery.pageNum = 1
      tableQuery.pageSize = 10
      await fetchData()
    }

    const onConfirmModal = () => {
      onCancelModal()
      onReset()
    }

    const onCancelModal = () => {
      pageType.value = BusinessPageTypeEnum.TABLE
      selectData.code = null
    }

    const handlePageChange = async () => {
      await fetchData()
    }

    async function fetchData() {
      tableLoading.value = true
      try {
        const data = await getDataList(tableQuery)
        const { items, pageInfo } = data as unknown as any
        tableData.value = items
        tableTotal.value = pageInfo
        tableLoading.value = false
      } catch (error) {
        tableLoading.value = false
        console.log(error)
      }
    }

    const onReset = async () => {
      tableQuery.pageNum = 1
      tableQuery.pageSize = 10
      tableQuery.addressType = null
      tableQuery.addressCode = null
      tableQuery.tagCode = null
      tableQuery.status = null
      tableQuery.deadlineStart = null
      tableQuery.deadlineEnd = null
      await fetchData()
    }

    const addData = () => {
      pageType.value = BusinessPageTypeEnum.ADD
    }

    onMounted(async () => {
      warehouseOptionData.value = await getWarehouseList()
      storeOptionData.value = await getStoreOptions()
      tagListData.value = await getTagList()
      await fetchData()
    })

    return {
      ...toRefs(status),
      tableLoading,
      tableData,
      tableTotal,
      tableQuery,
      tableColumns,
      pageType,
      selectData,
      warehouseOptionData,
      storeOptionData,
      addressOptionData,
      tagListData,
      addressChange,
      onSearch,
      onReset,
      handlePageChange,
      getColumns,
      addData,
      onConfirmModal,
      onCancelModal
    }
  },

  render() {
    const {
      tableColumns,
      tableLoading,
      tableData,
      tableTotal,
      tableQuery,
      pageType,
      selectData,
      warehouseOptionData,
      storeOptionData,
      addressOptionData,
      tagListData,
      addressChange,
      onSearch,
      onReset,
      getColumns,
      handlePageChange,
      addData,
      onConfirmModal,
      onCancelModal
    } = this
    return (
      <>
        {pageType === BusinessPageTypeEnum.TABLE && (
          <>
            <Card>
              <Row gutter={16} align='middle' type='flex'>
                <Col span={6}>
                  <FormItem label={'执行位置类型'}>
                    <Select
                      allowClear={true}
                      v-model={[tableQuery.addressType, 'value']}
                      placeholder={'请选择'}
                      options={addressTypeObj}
                      onChange={value => addressChange(value)}
                    />
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label={'执行位置'}>
                    <Select
                      allowClear={true}
                      v-model={[tableQuery.addressCode, 'value']}
                      placeholder={'请先选择执行位置类型'}
                      options={addressOptionData}
                    />
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label={'标签'}>
                    <Select allowClear={true} v-model={[tableQuery.tagCode, 'value']} options={tagListData}></Select>
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label={'任务完成状态'}>
                    <Select
                      v-model={[tableQuery.status, 'value']}
                      allowClear={true}
                      options={takeFinishStatus}
                      placeholder={'请选择'}
                    ></Select>
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label={'截止时间'}>
                    <DatePicker
                      v-model={[tableQuery.deadlineStart, 'value']}
                      format={'YYYY-MM-DD'}
                      valueFormat='YYYY-MM-DD'
                      placehoider={'请选择开始日期'}
                    />
                    <span>-</span>
                    <DatePicker
                      v-model={[tableQuery.deadlineEnd, 'value']}
                      format={'YYYY-MM-DD'}
                      valueFormat='YYYY-MM-DD'
                      placehoider={'请选择结束日期'}
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={18}>
                  {/* 'base:task-distribution:add'      'warehouse:purchase-order:add'   */}
                  <Button type={'primary'} onClick={addData} v-auth={['warehouse:purchase-order:add']}>
                    +新增
                  </Button>
                </Col>
                <Col span={6}>
                  <Space>
                    <Button type={'primary'} onClick={onSearch}>
                      查询
                    </Button>
                    <Button onClick={onReset}>重置</Button>
                  </Space>
                </Col>
              </Row>
            </Card>
            <Card style={{ marginTop: '16px' }}>
              <Table
                rowKey='id'
                columns={tableColumns}
                dataSource={unref(tableData)}
                loading={unref(tableLoading)}
                pagination={{
                  current: tableQuery.pageNum,
                  pageSize: tableQuery.pageSize,
                  total: unref(tableTotal.totalCount),
                  showTotal: () => `Total ${unref(tableTotal.totalCount)} items`,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  onChange: handlePageChange,
                  'onUpdate:current': current => (tableQuery.pageNum = current),
                  'onUpdate:pageSize': pageSize => (tableQuery.pageSize = pageSize)
                }}
              >
                {{
                  bodyCell: ({ column, record }) => getColumns(column, record)
                }}
              </Table>
            </Card>
          </>
        )}
        {pageType !== BusinessPageTypeEnum.TABLE && (
          <DataDetail
            code={selectData.code}
            businessType={pageType}
            onCancelModal={onCancelModal}
            onConfirmModal={onConfirmModal}
          />
        )}
      </>
    )
  }
})
export default TaskPublish
